import {
  Body,
  Request,
  Headers,
  Controller,
  HttpException,
  Post,
  Req,
  UseFilters,
  UseGuards,
  Header,
  Get,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { UserService } from './user.service';

import { ApiConfig, MiniProgramApi, ApiConfigKit } from 'tnwx';
import { MiniLoginDto } from './dto/mini-program-login.dto';
import { defaultConfig } from '@game/config/config';
import { ApiFail } from '@common/utils';
const envTxt = {
  WEB: '网站用户',
  WEAPP: '微信用户',
  ALIPAY: '支付宝用户',
  H5: 'WAP用户',
};

@ApiTags('MINI-用户')
@Controller()
@ApiBearerAuth()
export class UserController {
  constructor(
    private jwtService: JwtService,
    private authServe: UserService,
  ) {
    // 初始小程序配置
    const devApiConfig = new ApiConfig(
      defaultConfig.weixin.appid,
      defaultConfig.weixin.secret,
    );
    ApiConfigKit.putApiConfig(devApiConfig);
  }

  @Post('updateUser')
  @ApiOperation({ summary: '小程序用户信息更新' })
  async updateUserAction(
    @Body() miniLoginDto: MiniLoginDto,
    @Request() req: any,
  ) {
    console.log(miniLoginDto);
    let sessionData: any = {};

    const userId = req.user.userId;

    if (!userId) {
      throw new ApiFail(401, '未登录');
    }
    if (miniLoginDto.avatar) {
      sessionData.avatar = miniLoginDto.avatar;
    }
    if (miniLoginDto.nickName) {
      sessionData.nickName = miniLoginDto.nickName;
    }
    console.log(sessionData, userId);
    if (!sessionData) {
      throw new ApiFail(600, '数据没有变化');
    }
    const res = await this.authServe.update({ id: userId }, sessionData);

    console.log(res);

    if (res) {
      const user = await this.authServe.getUserInfo({ id: userId });
      sessionData = user;
      sessionData.userId = user.id;
      sessionData.openId = user.weixin_openId;

      delete sessionData.weixin_openId;
      delete sessionData.id;

      return {
        userInfo: sessionData,
      };
    } else {
      throw new ApiFail(600, '更新失败');
    }
  }

  @Get('getUserInfo')
  @ApiOperation({ summary: 'web-用户信息' })
  async getUserInfo(@Req() req: any) {
    return req.user;
  }
  @Get('getImgUrl')
  @ApiOperation({ summary: 'web-用户头像' })
  async getImgUrl(@Req() req: any) {

    return this.authServe.getImgUrl(req);
  }

  @Get('test')
  @ApiOperation({ summary: 'web-test信息' })
  async test(@Req() req: any) {
    return req.user;
  }

  @Post('isVip')
  async isVip(@Req() req: any) {
    let whereMap: any = {
      isDelete: 0,
    };
    const userId = req.user.userId;
    if (!userId) {
      throw new ApiFail(401, '未登录');
    }
    const user: any = await this.authServe.isValidUser({
      ...whereMap,
      id: userId,
    });
    if (!user) {
      throw new ApiFail(401, '不是本系统用户');
    }
    whereMap = {
      ...whereMap,
      userId: userId,
    };
    // 查个余额

    const data: any = await this.authServe.findVip(whereMap);
    //判断一下是否过期     //判断是不是本系统用户
    if (!data) {
      return {  amount: user.amount };
    }
    const currentTime = new Date().getTime();

    if (
      Number(data.startTime) <= currentTime &&
      Number(data.endTime) >= currentTime
    ) {
      return { ...data, amount: user.amount };
    } else {
      //会员已过期
      if (data.role == 1) {
        await this.authServe.updateRecord(whereMap, { role: -1 });
      }
      return { amount: user.amount };
    }
  }

  randomString(e) {
    e = e || 10;
    const t = '0123456789';
    const a = t.length;
    let n = '';
    for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
    return n;
  }
}
